package 哈希表;

import java.util.Arrays;

public class HashBuck {
    public static class Node{

       public int key;
       public int val;
       public Node next;
        public Node(int k, int val) {
            this.key = k;
            this.val = val;
        }
    }
    public final double LOAD_FACTOR = 0.75;
    public Node[]array;
    public int UsedSize;
    public HashBuck() {
        array = new Node[8];
    }
    public HashBuck(int x) {
        array = new Node[x];
    }
    public void put(int key,int val) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            //如果key相等就替换
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //头插法进行插入
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        UsedSize++;
        if(calculateLoadFactor() >= LOAD_FACTOR) {
            //扩容
            resize();
        }
    }
    //扩容
    private void resize() {
    //扩容需要注意什么？
        //每个元素都要重新的哈希
        Node[] newArray =new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                int index = cur.key % newArray.length;
                //头插
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
    //计算负载因子
    public double calculateLoadFactor() {
        return UsedSize*1.0/array.length;
    }

}
